from django.http import JsonResponse
from comment.comviews import com_views, err_response, success_response, format_response
from utils.dbutils import DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from comment.comservice import add_filter
from .sqlmap import *

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def notice_list(params):
    dict = {
        "user_id": "user_id",
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    sql = add_filter(NoteSqlMap.notice_list, params, ["query_str"], **NoteSqlMap.FILTER_PARAMS)
    sql += " order by t1.notice_time desc"
    sql = sql.format(**params)
    result = mysql_tools.select_all(sql)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        if res.get("notice_time"):
            res["notice_time"] = str(res.get("notice_time"))
    return success_response(result)


def notice_check(params):
    dict = {
        "notice_id": "notice_id",
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210)
    sql_check = NoteSqlMap.notice_check.format(**params)
    result = mysql_tools.select_one(sql_check)
    if not result:
        return success_response({})
    sql_read = NoteSqlMap.notice_read.format(**params)
    result["read_num"] = mysql_tools.select_one(sql_read)["read_num"]
    read_record = mysql_tools.select_one(NoteSqlMap.NOTICE_READ_CHECK.format(**params))
    if not read_record:
        create_read = NoteSqlMap.CREATE_READ_RECORD.format(**params)
        mysql_tools.execute_sql(create_read,commit=True)
    elif read_record["is_read"] == 0:
        UPDATE_READ_RECORD = NoteSqlMap.UPDATE_READ_RECORD.format(**params)
        mysql_tools.execute_sql(UPDATE_READ_RECORD,commit=True)
    result["notice_time"] = str(result["notice_time"])
    return success_response(result)

def notice_add(params):
    dict = {
        "content": "content",
        "user_id": "user_id",
        "receiver_id": "receiver_id",
        "is_top": "is_top",
        "status_id": "status_id",
        "title": "title",
        "type_id": "type_id"
    }
    null_params = {
        "url": "url"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if key == "url":
    #         continue
    #     if not val:
    #         return err_response(210)
    real_name = ""
    user_name = ""
    id_list = []
    for id in params.get("receiver_id").split(";"):
        id_list.append(int(id))
        name = mysql_tools.select_one(NoteSqlMap.FIND_NAME.format(**{"user_id": int(id)}))
        real_name += name.get("real_name") + ";"
        user_name += name.get("user_name") + ";"
    params["real_name"] = real_name[0:-1]
    params["user_name"] = user_name[0:-1]
    if not params.get("url"):       # url选填,如果没有url的话执行这个
        mysql_tools.execute_sql(NoteSqlMap.INSERT_NOTICE_NO.format(**params))
    else:                           # 有的话执行这个
        mysql_tools.execute_sql(NoteSqlMap.INSERT_NOTICE.format(**params))
    notice_id = mysql_tools.select_one(NoteSqlMap.GET_ID).get("id")
    for id_user in id_list:
        sql = NoteSqlMap.INSERT_RELATION.format(**{"relatin_user_id": id_user, "notice_id": notice_id})
        mysql_tools.execute_sql(sql, commit=True)
    return success_response({"notice_id": notice_id})



@format_response
def index(request):
    return com_views(request, {
        "notice_list": notice_list,
        "notice_check": notice_check,
        "notice_add": notice_add
    })
